package com.huanletao.quartz.execute;

import com.huanletao.quartz.entity.JobDetails;
import com.huanletao.quartz.schedule.QuartzDataManager;
import com.huanletao.quartz.utils.ReflectUtils;
import com.huanletao.quartz.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * description: DistributedExecuteJobQuartz <br>
 * date: 2022/7/4 18:28 <br>
 * author: 踏雪无痕 <br>
 * version: 1.0 <br>
 */
public class DistributedExecuteJobQuartz extends AbstractExecuteJobQuartz {

    private static final Logger logger = LoggerFactory.getLogger(DistributedExecuteJobQuartz.class);

    private  static ThreadLocal<Boolean> THREADLOCAL = new ThreadLocal<>();

    private final ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

    private final QuartzDataManager quartzDataManager = SpringUtils.getBean(QuartzDataManager.class);

    /**
     * @param jobDetails
     */
    public void before(JobDetails jobDetails) {
        logger.info("param= = {}", jobDetails);
        try {
            boolean flag = quartzDataManager.getJobExecuteFlag(jobDetails);
            logger.info("flag= {}", flag);
            THREADLOCAL.set(flag);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doExecute(JobDetails details) throws Exception {
        Boolean flag = THREADLOCAL.get();
        if (!flag) {
            logger.info("获取不到锁，不执行业务逻辑。over");
            return;
        }
        ReflectUtils.invokeMethod(details);
    }

    public void after(JobDetails jobDetails) {
        Boolean flag = THREADLOCAL.get();
        THREADLOCAL.remove();
        if (!flag) {
            return;
        }
        //修改恢复状态
        executor.schedule(() -> {
            try {
                boolean resumeflag = quartzDataManager.resumeExecuteFlag(jobDetails);
                logger.info("恢复标志:{}", resumeflag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 12, TimeUnit.SECONDS);

    }
}
